<?php

/**
 * Booking Model for Room Booking Component
 * 
 * @version 1.0
 * @package    Joomla
 * @subpackage RoomBooking
 * @copyright (C) 2011 Giovanni Marzulli
 * @license		GNU/GPL
 */
// No direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');

class RoomBookingModelBooking extends JModel {

    /**
     * Constructor that retrieves the ID from the request
     *
     * @access	public
     * @return	void
     */
    function __construct() {
        parent::__construct();

        $array = JRequest::getVar('cid', 0, '', 'array');
        $this->setId((int) $array[0]);
    }

    /**
     * Method to set the identifier
     *
     * @access	public
     * @param	int identifier
     * @return	void
     */
    function setId($id) {
        // Set id and wipe data
        $this->_id = $id;
        $this->_data = null;
    }

    /**
     * Method to get a booking record
     * @return object with data
     */
    function &getData() {
        // Load the data
        if (empty($this->_data)) {
            $query = ' SELECT * FROM #__roombooking_bookings ' .
                    '  WHERE id = ' . $this->_id;
            $this->_db->setQuery($query);
            $this->_data = $this->_db->loadObject();
        }
        if (!$this->_data) {
            $this->_data = new stdClass();
            $this->_data->id = 0;
            $this->_data->short_description = null;
            $this->_data->description = null;
            $this->_data->start = null;
            $this->_data->end = null;
            $this->_data->notes = null;
            $this->_data->repeat_type = null;
            $this->_data->repeat_until = null;
            $this->_data->series = null;
            $this->_data->id_room = null;
            $this->_data->id_user = null;
            $this->_data->total = null;
        }
        return $this->_data;
    }

    /**
     * Method to store a record
     *
     * @access	public
     * @return	boolean	True on success
     */
    function store() {

        $row = & $this->getTable();
        JRequest::setVar('start', JRequest::getVar('start_date') . ' ' . JRequest::getVar('start_hour') . ':' . JRequest::getVar('start_minute'));
        JRequest::setVar('end', JRequest::getVar('end_date') . ' ' . JRequest::getVar('end_hour') . ':' . JRequest::getVar('end_minute'));
        $data = JRequest::get('post');

        // Bind the form fields to the booking table
        if (!$row->bind($data)) {
            $this->setError($this->_db->getErrorMsg());
            return false;
        }

        // Make sure the booking record is valid
        if (!$row->check()) {
            $this->setError($this->_db->getErrorMsg());
            return false;
        }

        // Sets the error message
        if (!$row->store()) {
            $this->setError($row->getErrorMsg());
            return false;
        } else {
            $this->changeUserCost('save', $row->id);
        }

        return $row->id;
    }

    function changeUserCost($task, $id_booking) {
        $db = & JFactory::getDBO();
        //get total
        $query = 'SELECT b.total,b.id_user,rt.cancel_cost,rt.fee,b.start,b.end FROM #__roombooking_bookings AS b LEFT JOIN (#__roombooking_rooms AS r,#__roombooking_rooms_types AS rt) ON (b.id_room = r.id AND r.room_type_id = rt.id) WHERE b.id = ' . $id_booking;
        $db->setQuery($query);
        $results = $db->loadObjectList();
        if (count($results) > 0) {
            $total = $results[0]->total;
            $id_user = $results[0]->id_user;
            $start = $results[0]->start;
            $end = $results[0]->end;

            //loop
            $num_day = ceil(abs((strtotime($start) - strtotime($end)) / (24 * 60 * 60)));

            $start_time = strtotime($start);
            $end_time = strtotime($end);
            if(date('Y',$start_time) == date('Y',$end_time) && date('m',$start_time) == date('m',$end_time)){
                $this->changeCostRow($task, $id_user, date('Y',$start_time), date('m',$start_time), $total,$results[0]->cancel_cost,$results[0]->fee);
            }else{
                $month = $start_time;
                while ($month <= $end_time) {
                    if($month == $start_time)$cost = (int)((30 - date('d',$month))*$total/$num_day);
                    else $cost = (int)(30*$total/$num_day);
                    $this->changeCostRow($task, $id_user, date('Y',$month), date('m',$month), $cost,$results[0]->cancel_cost,$results[0]->fee);
                    $month = strtotime("+1 month", $month);
                }
                if(strtotime(date('Y-m'.'-01')) <= $end_time){
                    $cost = (int)(date('d',$end_time)*$total/$num_day);
                    $this->changeCostRow($task, $id_user, date('Y',$end_time), date('m',$end_time), $cost,$results[0]->cancel_cost,$results[0]->fee);
                }
            }
        }
    }

    function changeCostRow($task, $id_user, $year, $month, $cost,$cancel_cost,$fee) {
        $id_user = (int) $id_user;
        $year = (int) $year;
        $month = (int) $month;
        $cost = (int) $cost;
        $db = &JFactory::getDBO();
        $query = 'select * from #__roombooking_costs where id_user = ' . $id_user . ' AND month = ' . $month . ' AND year = ' . $year;
//        $this->roomLog($query);
        $db->setQuery($query);
        $data = $db->loadObjectList();
//        $this->roomLog("num row:".$db->loadObjectList());
        if (count($data) == 0)
            $query = 'insert into #__roombooking_costs (id_user,year,month,cost) values (' . $id_user . ',' . $year . ',' . $month . ',' . $cost . ')';
        else {
            if ($task == 'save')
                $op = '+';
            else{
                $op = '-';
                $cost = $cost - $cancel_cost - $fee;
            }
            $query = 'update #__roombooking_costs set cost = cost ' . $op . ' ' . $cost . ' where id_user = ' . $data[0]->id_user . ' AND month = ' . $data[0]->month . ' AND year = ' . $data[0]->year;
            $this->roomLog($query);
        }
        $db->setQuery($query);
        $db->query();
    }

    function roomLog($comment) {
        jimport('joomla.error.log');
        // Define the file name as a PHP constant
        define('ROOM_LOG', 'room.log.' . date('Y_m_d') . '.php');

        $log = &JLog::getInstance(ROOM_LOG);

        // Just adding a comment
        $log->addEntry(array('comment' => $comment));
    }

    /**
     * Method to delete record(s)
     *
     * @access	public
     * @return	boolean	True on success
     */
    function delete() {

        $id = JRequest::getVar('id');
        if ($id) {
            $row = & $this->getTable();

            if (!$row->delete($id)) {
                $this->setError($row->getErrorMsg());
                return false;
            }
            return true;
        } else {
            $cids = JRequest::getVar('cid', array(0), 'post', 'array');

            $row = & $this->getTable();

            if (count($cids)) {
                foreach ($cids as $cid) {
                    $this->changeUserCost('delete', $cid);
                    if (!$row->delete($cid)) {
                        $this->setError($row->getErrorMsg());
                        return false;
                    }
                }
            }
            return true;
        }
    }

    function deleteSeries($series) {
        $query = 'DELETE FROM #__roombooking_bookings WHERE series=' . $series;
        $this->_db->setQuery($query);
        return $this->_db->query($query);
    }

    /**
     * Method to check if a booking exists
     *
     * @access	public
     * @return	boolean	True on exist
     */
    function exists($id_booking) {

        $query = ' SELECT id FROM #__roombooking_bookings ' .
                '  WHERE id = ' . $id_booking;
        $this->_db->setQuery($query);
        $id = $this->_db->loadObject();

        if ($id)
            return true;
        else
            return false;
    }

    /**
     * Method to get owner user id  of booking
     *
     * @access	public
     * @return	boolean	True on exist
     */
    function getUserID($id_booking) {

        $query = ' SELECT id_user FROM #__roombooking_bookings ' .
                '  WHERE id = ' . $id_booking;
        $this->_db->setQuery($query);
        $row = $this->_db->loadObject();

        return $row->id_user;
    }

}
